<template>
    <el-dialog title="SRM-送货单明细管理—打印" v-model="visible" width="65%"
               :close-on-click-modal="false" draggable>
        <div style="height: 600px">
          <el-row>
            <div class="mb8" style="width: 100%">
              <el-button icon="folder-add" type="primary" class="ml10" @click="addmembers">
                {{ $t('srmAsnD.add') }}
              </el-button>
              <el-button icon="folder-add" type="warning" class="ml10" @click="srmAsnBatchUpdate">
                {{ $t('srmAsnD.batchUpdate') }}
              </el-button>
            </div>
          </el-row>
          <el-table :data="state.dataList" v-loading="state.loading" border style="width: 100%"
                    :cell-style="tableStyle.cellStyle" :header-cell-style="tableStyle.headerCellStyle"
                    :highlight-current-row="true"
                    @row-click="clickRow"
                    @selection-change="selectionChangeHandle"
                    @sort-change="sortChangeHandle">
            <el-table-column type="selection" width="40" align="center" />
            <el-table-column type="index" label="#" width="60"/>
            <el-table-column prop="asnCode" :label="$t('podetail.asnCode')" show-overflow-tooltip  width="200"/>
            <el-table-column prop="barcodeQty" :label="$t('srmAsnD.barcodeQty')" show-overflow-tooltip  width="150">
              <template #default="scope">
                <div v-if="scope.row.editable">
                  <el-input-number
                      v-model="scope.row.barcodeQty"
                      @blur="handleUpdateFinished(scope.row)"
                      @change="checkQuantity(scope.row)"
                      @keyup.enter="handleUpdateFinished(scope.row)"
                      :min="0"
                      :class="{ 'input-error': isError(scope.row) }"
                  />
                </div>
                <div v-else>
                  <span>{{ scope.row.barcodeQty}}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="asnQty" :label="$t('podetail.asnQty')" show-overflow-tooltip  width="120"/>
            <el-table-column prop="barcode" :label="$t('srmAsnD.barcode')" show-overflow-tooltip width="180"/>
            <el-table-column prop="productDate" :label="$t('srmAsnD.productionDate')" show-overflow-tooltip  width="150">
              <template #default="scope">
                <div v-if="scope.row.editable">
                  <el-date-picker style="width: 100%;height: 100%"
                                  v-model="scope.row.productDate"
                                  type="date"
                                  placeholder="选择日期时间"
                                  @blur="handleUpdateFinished(scope.row)"
                                  @change="handleUpdateFinished(scope.row)"
                                  value-format="YYYY-MM-DD"
                                  :clearable="false"
                                  size="default"
                  />
                </div>
                <div v-else>
                  <span>{{ scope.row.productDate }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="produceBatch" :label="$t('srmAsnD.produceBatch')" show-overflow-tooltip  width="120">
              <template #default="scope">
                <div v-if="scope.row.editable" >
                  <el-input
                      v-model="scope.row.produceBatch"
                      @blur="handleUpdateFinished(scope.row)"
                      @keyup.enter="handleUpdateFinished(scope.row)"
                      size="default"
                  />
                </div>
                <div v-else>
                  <span>{{ scope.row.produceBatch}}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="productEquipment" :label="$t('srmAsnD.productEquipment')" show-overflow-tooltip width="120">
              <template #default="scope">
                <div v-if="scope.row.editable" >
                  <el-input
                      v-model="scope.row.productEquipment"
                      @blur="handleUpdateFinished(scope.row)"
                      @keyup.enter="handleUpdateFinished(scope.row)"
                      size="default"
                  />
                </div>
                <div v-else>
                  <span>{{ scope.row.productEquipment}}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="poCode" :label="$t('poheader.poCode')" show-overflow-tooltip width="160"/>
            <el-table-column prop="contractNumber" :label="$t('poheader.contractNumber')" show-overflow-tooltip width="150"/>
            <el-table-column prop="remark" :label="$t('srmAsnD.remark')" show-overflow-tooltip  width="120">
              <template #default="scope">
                <div v-if="scope.row.editable" >
                  <el-input
                      v-model="scope.row.remark"
                      @blur="handleUpdateFinished(scope.row)"
                      @keyup.enter="handleUpdateFinished(scope.row)"
                      size="default"
                  />
                </div>
                <div v-else>
                  <span>{{ scope.row.remark}}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="80">
              <template #default="scope">
                <Delete @click="delmembers(scope.$index, scope.row)"
                        style="width: 1em; height: 1em; margin-right: 8px;color: #f56c6c;" />
              </template>
            </el-table-column>
          </el-table>
        </div>
<!--        <pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination"/>-->
        <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" icon="check"  @click="onSubmit" :disabled="loading">{{ $t('srmAsnD.submit') }}</el-button>
                <el-button icon="close" @click="visible = false"> {{ $t('srmAsnD.cancel') }}</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts" name="SrmPoheaderDialog">
import {useMessage} from "/@/hooks/message";
import {BasicTableProps, useTable} from "/@/hooks/table";
import {insertOrUpdateBatch, selectByAsnDId} from "/@/api/platform/srm/srmAsnH";
import {ElMessage} from "element-plus";

const emit = defineEmits(['refresh']);

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false)
const loading = ref(false)

// 多选变量
const selectObjs = ref([]) as any
const multiple = ref(true)
const selectedRows =ref([]) as any
const indices =ref([]) as any

// 多选事件
const selectionChangeHandle = (objs: { id: string }[]) => {
    selectObjs.value = objs.map(({id}) => id);
    multiple.value = !objs.length;
    selectedRows.value = objs;
    indices.value = state.dataList?.reduce((acc, item, index) => {
        if (objs.includes(item)) {
            acc.push(index);
        }
        return acc;
    }, []);
};

// 在这里更新数据源
const handleUpdateFinished = (row) => {
    row.editable = false;
}
//判断输入数量不能大于送货单数量
const checkQuantity = (currentRow) => {
    const total = state.dataList?.reduce((sum, row) => sum + row.barcodEqty, 0);
    const assignableNum = currentRow.asnQty; // 假设每行都有 asnQty 属性

    if (total > assignableNum) {
        ElMessage({ message: `条码数量不能大于送货单数量 ${currentRow.asnQty}` });
        currentRow.barcodEqty = Math.max(currentRow.barcodEqty - (total - assignableNum), 0); // 重新调整当前行的值
    }
}
const isError = (row) => {
    return row.barcodEqty > row.asnQty;  // 返回是否超出可分配数量
}

const state: BasicTableProps = reactive<BasicTableProps>({
    queryForm: {},
    pageList: selectByAsnDId,
    isPage: false
})

//  table hook
const {
    getDataList,
    currentChangeHandle,
    sizeChangeHandle,
    sortChangeHandle,
    tableStyle
} = useTable(state)

// 新增自动生成送货单数据
const addmembers = () => {
    state.dataList.push(
        {
            asnCode:  form.asnCode,
            asnHId:  form.asnHId,
            asnDId:  form.id,
            asnQty:  form.asnQty,
            barcode: '自动生成'+(state.dataList?.length +1),
            barcodEqty: null,
            productDate: null,
            produceBatch: '',
            productEquipment: '',
            remark: ''
        }
    )
}
// 删除操作
const delmembers = (index, row) => {
    state.dataList.splice(index, 1);
    ElMessage({ message: '删除成功' });
}

// 提交表单数据
const form = reactive({
    asnCode:'',
    asnQty:'',
    id:'',
    asnHId:'',
});

// 打开弹窗
const openDialog = (id,asnCode,asnQty,asnHId) => {
    //查询参数id
    state.queryForm.id = id
    form.id = id
    form.asnCode = asnCode
    form.asnQty = asnQty
    form.asnHId = asnHId
    getDataList(false)
    visible.value = true

    // 重置表单数据
    nextTick(() => {
        dataFormRef.value?.resetFields();
    });

};

// 提交
const onSubmit = async () => {
    try {
        let params = {
            id : form.id,
            srmAsnBarcodes : state.dataList
        }
        loading.value = true;
        await insertOrUpdateBatch(params);
        useMessage().success('保存成功');
        visible.value = false;
        emit('refresh');
    } catch (err: any) {
        useMessage().error(err.msg);
    } finally {
        loading.value = false;
    }
};

// 点击行的时候触发
const clickRow = (row: any) => {
    //遍历行是否可否可编辑
    state.dataList?.forEach(item =>{
        if(item.barcode == row.barcode){
            item.editable = true;
        }else {
            item.editable = false;
        }
    })
}

//批量更新
const srmAsnBatchUpdate = () => {
    var rows = selectedRows.value;
    if(rows.length  < 2){
        return ElMessage.error('请至少选中两条送货单！');
    }
    let productDateList = [];
    let remarkList = [];    //备注
    let productEquipment = []; //生产设备集合
    let produceBatch = []; //生产设备集合

    rows.forEach(x=>{
        productDateList.push(x.productDate)
        remarkList.push(x.remark)
        productEquipment.push(x.productEquipment)
        produceBatch.push(x.produceBatch)
    })

    //首先判断三个数组是不是都为空
    if(productDateList.every(x => x == '' || x== null) && remarkList.every(x => x == '' || x== null) && productEquipment.every(x => x == '' || x== null)){
        return ElMessage.error('选中数据生产日期，生产设备，备注都为空！');
    }

    // 三个数组去重 Remover
    let productDateListRemover = [...new Set(productDateList)].filter(x => { return x !== null && x !== undefined && x !== ''});
    let remarkListRemover = [...new Set(remarkList)].filter(x => { return x !== null && x !== undefined && x !== ''});
    let productEquipmentRemover = [...new Set(productEquipment)].filter(x => { return x !== null && x !== undefined && x !== ''});
    let produceBatchRemover = [...new Set(produceBatch)].filter(x => { return x !== null && x !== undefined && x !== ''});

    if(productDateListRemover.length > 1 || remarkListRemover.length > 1 || productEquipmentRemover.length > 1|| produceBatchRemover.length > 1){
        return ElMessage.error('选中数据生产日期，生产批次，生产设备，备注存在不同数据！');
    }

    rows.forEach(x=>{
        x.productDate = productDateListRemover[0]
        x.remark = remarkListRemover[0]
        x.productEquipment = productEquipmentRemover[0]
        x.produceBatch = produceBatchRemover[0]
    })
    //根据下标更新
    indices.value.forEach(x=>{
      state.dataList[x].productDate = rows[0].productDate
      state.dataList[x].remark = rows[0].remark
      state.dataList[x].productEquipment = rows[0].productEquipment
      state.dataList[x].produceBatch = rows[0].produceBatch
    })

}
// 暴露变量
defineExpose({
    openDialog
});
</script>
<style scoped>
.input-error {
    border: 1px solid red; /* 标红的边框 */
    color: red;
}
</style>